package multidraw;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import multidraw.model.DrawingCanvasModel;
import multidraw.model.ModelObserver;
import multidraw.model.Shape;
import multidraw.tools.Tool;



public class DrawingCanvasView extends JComponent implements ModelObserver {		
	DrawingCanvasModel myModel;
	DrawingCanvasController myController;

	public DrawingCanvasView(DrawingCanvasModel model) {	
		setFocusable(true);
		this.myModel = model;
		
		myModel.attachObserver(this);
		
		myController = makeController();

		addDrawingCanvasListener(myController);
	}
	
	protected DrawingCanvasController makeController() {
	      return new DrawingCanvasController(myModel, this);
	}
	
	protected void addDrawingCanvasListener(DrawingCanvasController controller) {
		if (controller != null) {
			addMouseListener(controller);
			addMouseMotionListener(controller);
			addKeyListener(controller);
		}
	}

	public void updateContent() {
		//invalidate();
		//JOptionPane.showMessageDialog(null, "Canvas being updated " + myModel.getSelectedObjectIndex());
		//this.revalidate();
		System.out.println("Revalidating ... ");
		this.repaint();
		//this.updateUI();
	}

	
	public void paintComponent(Graphics g) {
		super.paintComponent(g); //This is a MUST, otherwise the system will behave strangely.
		System.out.println("Redrawing ... ");
		List<Shape> shapes = myModel.getData();

		for (int i = 0; i < shapes.size(); i++) {
			Shape s = shapes.get(i);
			
			s.draw(g, false);
		}
		
		//draw the highlight for selected objects.
		Shape selectedShape = myModel.getSelectedObject();
		if (selectedShape != null) 
			selectedShape.drawControlPoints(g);
		
		//draw the outline of the current drawing shape if any
		Tool t = myModel.getCurrentTool();
		if (t != null) {
			//get the shape
			Shape s = t.getShape();
			System.out.println("Current tool: " + t);
			System.out.println("Current tool shape: " + s);
			if (s != null) {
				//draw outline
				s.drawOutline(g);
			}
		}
		
	}
	
	public boolean isFocusTraversable()
	{
		return true;
	}
	
}
